package com.spider.task;

import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.StringUtils;

import com.db.mongodb.MMongoDB;
import com.senEmail.MailInfo;
import com.senEmail.SendMail;
import com.spider.base.BaseResult;
import com.spider.bean.ZhilianJobBean;
import com.spider.queue.SpiderBlockQueue;
import com.spider.util.SpiderCondition;



public class SendEmailTask implements Runnable {
	
	private String emailContent = "";
	public SendEmailTask(String content){
		this.emailContent = content;
	}
	
	public void run() {
		sendEmail();
	}
	
	/**
	 * 发送邮件
	 */
	public void sendEmail(){
		ZhilianJobBean bean = getBaseResultFromMongo();
		if(bean==null)
			return ;
		if(StringUtils.isBlank(bean.getEmail()) || bean.getEmail().contains(SpiderCondition.EMAIL_NOT_PWSS_WORD))
				return;
		MailInfo mailinfo=new MailInfo();  
		//--设置邮件服务器开始  
		mailinfo.setMailServerHost(SpiderCondition.EMAIL_SERVER);  
		mailinfo.setMailServerPort(SpiderCondition.EMAIL_SERVER_PORT);  
		mailinfo.setValidate(true);  
		mailinfo.setUserName(SpiderCondition.EMAIL_USERNAME);  
		mailinfo.setPassword(SpiderCondition.EMAIL_PASSWD);  
		//--设置邮件服务器结束  
		
		mailinfo.setFromAddress(SpiderCondition.EMAIL_FROM_ADDRESS);//邮件发送者的地址  
		//设置接受用户  
		String []ToAddress={bean.getEmail()};  
//		String []ToAddress={"ztfzjj@163.com"};  
		mailinfo.setToAddress(ToAddress);  
		//设置附件  
		// String []attach={"F:\\login.properties"};  
		// mailinfo.setAttachFileNames(attach);  
		mailinfo.setSubject("应聘java工程师\\互联网开发工程师");  
		mailinfo.setContent(emailContent);//网页内容  
		SendMail sm=new SendMail();  
		if(sm.sendAttach(mailinfo))  
		    System.out.println("邮件发送成功" + bean.getCompanyName() +"   "+bean.getJobName());  
		else{
			System.out.println("邮件发送失败");
			MMongoDB db = new MMongoDB();
			db.save(SpiderCondition.JOB_FALSE_EMAIL_TABLE_NAME, bean);
		} 
		  
	} 
	
	/** 从队列中获得 队列中存的对象
	 * @return
	 */
	public BaseResult getBaseResult(){
		BaseResult result = null;
		try {
			result = (BaseResult) SpiderBlockQueue.emailQueue.poll(1, TimeUnit.SECONDS);
			if(result==null)
				return null;
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return result;
		
	}
	
	/** 从队列中获得 队列中存的对象
	 * @return
	 */
	public ZhilianJobBean getBaseResultFromMongo(){
		ZhilianJobBean result = null;
			MMongoDB db = new MMongoDB();
			ZhilianJobBean fields = new ZhilianJobBean();
			fields.setCompanyName("1");
			fields.setJobName("1");
			fields.setJobUrl("1");
			fields.setEmail("1");
			result = db.findOne(SpiderCondition.JOB_EMAIL_BEAN_TABLE_NAME, new ZhilianJobBean(), fields);
			if(result==null)
				return null;
			db.remove(SpiderCondition.JOB_EMAIL_BEAN_TABLE_NAME, result);
		return result;
		
	}
	
}
